<template>
  <div class="bridge">
    <el-button
      size="small"
      type="primary"
      icon="el-icon-plus"
      @click="addEquipment"
      style="float:right;margin-bottom:20px;"
    >新增桥联</el-button>
    <el-table
      :data="tableData"
      :header-cell-style="{background: '#8595B9',color: '#fff',height:'44px'}"
      class="tableTop"
      max-height="500"
      stripe
    >
      <el-table-column label="桥联名称" prop="name" show-overflow-tooltip></el-table-column>
      <el-table-column label="桥联编码" prop="code" show-overflow-tooltip></el-table-column>
      <el-table-column label="桥联类型" prop="bridgeTypeName" show-overflow-tooltip></el-table-column>
      <el-table-column label="桥联全长(m)" prop="length" show-overflow-tooltip></el-table-column>
      <el-table-column label="缩略图" prop="area" show-overflow-tooltip>
        <template slot-scope="scope">
          <el-image
            style="width: 50px; height: 50px;margin-top:10px;"
            :src="download + scope.row.realisticPictureList[0].path"
            :preview-src-list="[download + scope.row.realisticPictureList[0].path]"
            v-if="scope.row.realisticPictureList.length > 0"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column label="区域" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>
            {{scope.row.provinceName}}
            <span
              v-if="scope.row.municipalityName && scope.row.municipalityName !== ''"
            >/{{scope.row.municipalityName}}</span>
            <span
              v-if="scope.row.regionName && scope.row.regionName !== ''"
            >/{{scope.row.regionName}}</span>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="备注" prop="desc" show-overflow-tooltip></el-table-column>
      <el-table-column label="是否启用" prop="status" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{scope.row.status === 1? '启用' : scope.row.status === 0 ? '停用' : ''}}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-tooltip content="修改">
            <el-button type="text" icon="el-icon-edit-outline" @click="edit(scope.row)"></el-button>
          </el-tooltip>
          <el-tooltip content="删除">
            <el-button
              type="text"
              icon="el-icon-delete"
              style="color:red !important"
              @click="removeBridge(scope.row)"
            ></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <!-- 新增桥联 -->
    <vx-popup
      :title="addtitle"
      width="900px"
      @close="cancelFormSubmit"
      :active.sync="dialogVisible"
      @confirmPopup="submit"
      @cancelPopup="cancelFormSubmit"
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-row justify="space-between" :gutter="24">
          <el-col :span="8">
            <el-form-item label="桥联名称:" prop="name">
              <el-input v-model="ruleForm.name" size="small" placeholder="请输入侨联名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="桥联编码:" prop="code">
              <el-input v-model="ruleForm.code" size="small" placeholder="请输入侨联编号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="桥联全长:" prop="length">
              <el-input v-model="ruleForm.length" size="small" placeholder="请输入侨联全长"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row justify="space-between" :gutter="24">
          <el-col :span="8">
            <el-form-item label="桥联规范:" prop="standardId">
              <el-select
                v-model="ruleForm.standardId"
                placeholder="请选择桥联规范"
                size="small"
                @change="changeStandardId"
              >
                <el-option
                  v-for="(item,index) in standardList"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="桥联类型:" prop="bridgeTypeId">
              <el-select
                v-model="ruleForm.bridgeTypeId"
                placeholder="请选择桥联类型"
                size="small"
                @change="changeType"
              >
                <el-option
                  v-for="(item,index) in bridgeList"
                  :key="index"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="桥联种类:" prop="bridgeKindId">
              <el-select
                v-model="ruleForm.bridgeKindId"
                placeholder="请选择桥联种类"
                size="small"
                @change="changeKind"
              >
                <el-option
                  v-for="(item,index) in kindList"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row justify="space-between" :gutter="24">
          <el-col :span="8">
            <el-form-item label="养护类别:" prop="maintenanceType">
              <el-select
                v-model="ruleForm.maintenanceType"
                placeholder="请选择养护类别"
                size="small"
                @change="changeMaintenanceType"
              >
                <el-option
                  v-for="(item,index) in mainList"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="养护级别:" prop="maintenanceLevel">
              <el-select v-model="ruleForm.maintenanceLevel" placeholder="请选择养护级别" size="small">
                <el-option
                  v-for="(item,index) in typeList"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="运行状态:" prop="status">
              <el-radio-group v-model="ruleForm.status" size="small">
                <el-radio :label="0">停用</el-radio>
                <el-radio :label="1">启用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row justify="space-between" :gutter="24">
          <el-col :span="8">
            <el-form-item label="所属省:" prop="provinceCode">
              <el-select
                v-model="ruleForm.provinceCode"
                placeholder="请选择省"
                size="small"
                @change="changeRuleRegion(ruleForm.provinceCode)"
              >
                <el-option
                  v-for="item in options"
                  :key="item.regionCode"
                  :label="item.regionName"
                  :value="item.regionCode"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="所属市:" prop="municipalityCode">
              <el-select
                v-model="ruleForm.municipalityCode"
                placeholder="请选择市"
                size="small"
                @change="changeRuleCity(ruleForm.municipalityCode)"
              >
                <el-option
                  v-for="item in ruleCityOptions"
                  :key="item.regionCode"
                  :label="item.regionName"
                  :value="item.regionCode"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="所属区:" prop="regionCode">
              <el-select
                v-model="ruleForm.regionCode"
                placeholder="请选择区"
                size="small"
                @change="changeRuleArea(ruleForm.regionCode)"
              >
                <el-option
                  v-for="item in ruleAreaOptions"
                  :key="item.regionCode"
                  :label="item.regionName"
                  :value="item.regionCode"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label="桥联位置:" prop="address">
              <div v-if="addtitle === '新增桥联'">
              <el-input
                v-model.trim="ruleForm.address"
                id="suggestId"
                name="ruleForm.address"
                size="small"
              ></el-input>
              <div class="map_box" id="map"></div>
              </div>
              <div v-else style="width:360px;">
                <span>{{ruleForm.address}}</span>
                <el-button icon="el-icon-place" @click="setAddress" type="text" style="margin-left:20px"></el-button>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="桥联简介:" prop="desc">
          <el-input
            type="textarea"
            v-model="ruleForm.desc"
            maxlength="500"
            show-word-limit
            size="small"
          ></el-input>
        </el-form-item>
        <el-form-item label="桥联图片:">
          <el-upload
            :action="upload"
            list-type="picture-card"
            :on-remove="removeRender"
            :on-success="handleSuccessRender"
            :file-list="imgList"
            :limit="1"
          >
            <i class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
    </vx-popup>
      <vx-popup
      title="选择地理位置"
      width="800px"
      @close="cancel"
      :active.sync="mapContent"
      @confirmPopup="submitMap"
      @cancelPopup="cancel"
      style="z-index:51003 !important" 
    >
    <el-input
      v-model.trim="address"
      id="suggest"
      name="address"
      size="small"
      style="width:200px;"
    ></el-input>
    <div class="map_box" id="mapContent"></div>
     </vx-popup>
  </div>
</template>
<script>
// 滚动条
import VuePerfectScrollbar from "vue-perfect-scrollbar";
import base from "../../../api/base";
export default {
  name: "bridgeLink",
  props: {
    ownId: {
      type: String
    },
    pId: {
      type: String
    }
  },
  data() {
    return {
      upload: base.UPLOADURL,
      download: base.DOWNLOADURL,
      imgList: [],
      maxHeight: 0,
      addtitle: "新增桥联",
      dialogVisible: false,
      mapContent: false, 
      options: [],
      ruleCityOptions: [],
      ruleAreaOptions: [],
      loading: true,
      index: false,
      tableData: [],
      total: 0,
      add: false,
      bridgeList: [],
      standardList: [
        {
          label: "城市桥梁规范",
          value: "0"
        },
        {
          label: "公路桥梁规范",
          value: "1"
        }
      ],
      kindList: [
        {
          label: "立交桥",
          value: "0"
        },
        {
          label: "跨江跨河桥",
          value: "1"
        }
      ],
      mainList: [
        {
          label: "Ⅰ类养护",
          value: "0"
        },
        {
          label: "Ⅱ类养护",
          value: "1"
        },
        {
          label: "Ⅲ类养护",
          value: "2"
        },
        {
          label: "Ⅳ类养护",
          value: "3"
        },
        {
          label: "Ⅴ类养护",
          value: "4"
        }
      ],
      typeList: [],
      typeList1: [
        {
          value: "5",
          label: "合格级"
        },
        {
          value: "6",
          label: "不合格级"
        }
      ],
      typeList2: [
        {
          value: "0",
          label: "A级"
        },
        {
          value: "1",
          label: "B级"
        },
        {
          value: "2",
          label: "C级"
        },
        {
          value: "3",
          label: "D级"
        },
        {
          value: "4",
          label: "E级"
        }
      ],
      ruleForm: {
        name: "",
        code: "",
        bridgeTypeId: "",
        bridgeTypeName: "",
        bridgeKindId: "",
        bridgeKindName: "",
        length: "",
        address: "",
        lat: "",
        lng: "",
        status: 1,
        desc: "",
        maintenanceType: "",
        maintenanceLevel: "",
        regionCode: "",
        municipalityCode: "",
        provinceCode: "",
        regionName: "",
        municipalityName: "",
        provinceName: "",
        standardId: "",
        standardName: "",
        realisticPictureList: []
      },
      rules: {
        name: [{ required: true, message: "请输入桥联名称", trigger: "blur" }],
        code: [{ required: true, message: "请输入桥联编码", trigger: "blur" }],
        length: [
          { required: true, message: "请输入桥联长度", trigger: "blur" }
        ],
        desc: [{ required: true, message: "请输入桥联简介", trigger: "blur" }],
        standardId: [
          { required: true, message: "请选择桥联规范", trigger: "change" }
        ],
        bridgeTypeId: [
          { required: true, message: "请选择桥联类型", trigger: "change" }
        ],
        bridgeKindId: [
          { required: true, message: "请选择桥联种类", trigger: "change" }
        ],
        provinceCode: [
          { required: true, message: "请选择所属省", trigger: "change" }
        ],
        municipalityCode: [
          { required: true, message: "请选择所属市", trigger: "change" }
        ],
        maintenanceType: [
          { required: true, message: "请选择养护类别", trigger: "change" }
        ],
        maintenanceLevel: [
          { required: true, message: "请选择养护级别", trigger: "change" }
        ],
        regionCode: [
          { required: true, message: "请选择所属区", trigger: "change" }
        ],
        address: [
          { required: true, message: "请输入桥联位置", trigger: "blur" }
        ],
        status: [
          { required: true, message: "请选择运行状态", trigger: "change" }
        ]
      },
      userlocation: { lng: "", lat: "" },
       address:'',
      location:{lng: '', lat:''},
      groupId: ""
    };
  },
  created() {
    this.getArea(100000, data => {
      this.options = data;
    });
    this.queryAllBridgeLink();
  },
  mounted() {
    this.$nextTick(function() {
      var th = this;
      // 创建Map实例
      var map = new BMap.Map("map");
      // 初始化地图,设置中心点坐标，
      map.centerAndZoom("南京", 15);
      map.enableScrollWheelZoom();
      var ac = new BMap.Autocomplete({
        //建立一个自动完成的对象
        input: "suggestId",
        location: map
      });
      var myValue;
      ac.addEventListener("onconfirm", function(e) {
        //鼠标点击下拉列表后的事件
        var _value = e.item.value;
        myValue =
          _value.province +
          _value.city +
          _value.district +
          _value.street +
          _value.business;
        th.ruleForm.address = myValue;
        setPlace();
      });
      function setPlace() {
        map.clearOverlays(); //清除地图上所有覆盖物
        function myFun() {
          th.userlocation = local.getResults().getPoi(0).point; //获取第一个智能搜索的结果
          map.centerAndZoom(th.userlocation, 18);
          map.addOverlay(new BMap.Marker(th.userlocation)); //添加标注
          th.ruleForm.lng = th.userlocation.lng;
          th.ruleForm.lat = th.userlocation.lat;
        }
        var local = new BMap.LocalSearch(map, {
          //智能搜索
          onSearchComplete: myFun
        });
        local.search(myValue);
      }
    });
  },
  components: {
    VuePerfectScrollbar
  },
  methods: {
    //省市查询
    getArea(id, callback) {
      this.$api.bridge.queryBridgeRegion({ parentId: id }).then(res => {
        if (res.data.success) {
          return callback(res.data.data);
        }
      });
    },
    changeRuleRegion(val) {
      this.ruleAreaOptions = [];
      this.ruleForm.regionCode = "";
      this.ruleForm.regionName = "";
      this.ruleCityOptions = [];
      this.ruleForm.municipalityCode = "";
      this.ruleForm.municipalityName = "";
      this.getArea(val, data => {
        this.ruleCityOptions = data;
      });
      this.options.map(v => {
        if (v.regionCode === val) {
          this.ruleForm.provinceName = v.regionName;
        }
      });
    },
    changeRuleCity(val) {
      this.ruleAreaOptions = [];
      this.ruleForm.regionCode = "";
      this.ruleForm.regionName = "";
      this.getArea(val, data => {
        this.ruleAreaOptions = data;
      });
      this.ruleCityOptions.map(v => {
        if (v.regionCode === val) {
          this.ruleForm.municipalityName = v.regionName;
        }
      });
    },
    changeRuleArea(val) {
      this.ruleAreaOptions.map(v => {
        if (v.regionCode === val) {
          this.ruleForm.regionName = v.regionName;
        }
      });
    },
    //桥梁规范
    changeStandardId(val) {
      this.ruleForm.bridgeTypeId = "";
      this.queryBridgeTypeList(val);
      this.standardList.map(v => {
        if (v.value === val) {
          this.ruleForm.standardName = v.label;
        }
      });
    },
    changeType(val) {
      this.bridgeList.map(v => {
        if (v.id === val) {
          this.ruleForm.bridgeTypeName = v.name;
        }
      });
    },
    changeKind(val) {
      this.kindList.map(v => {
        if (v.value === val) {
          this.ruleForm.bridgeKindName = v.label;
        }
      });
    },
    //养护类型
    changeMaintenanceType(val) {
      this.ruleForm.maintenanceLevel = "";
      if (val === "0") {
        this.typeList = this.typeList1;
      } else {
        this.typeList = this.typeList2;   
      }
    },
    //桥梁类型
    queryBridgeTypeList(id) {
      this.$api.bridge.queryBridgeTypeList({ standardId: id }).then(res => {
        if (res.data.success) {
          this.bridgeList = res.data.data[0];
        }
      });
    },
    //桥组查询
    queryAllBridgeLink() {
      let data = {
        ownId: this.ownId,
        pId: this.pId
      };
      this.$api.bridge.queryAllBridgeLink(data).then(res => {
        if (res.data.success) {
          this.tableData = res.data.data[0];
        }
      });
    },
    changeCurrent(val) {
      this.pageNum = val;
      this.queryBridgeGroup();
    },
    //获取桥梁
    queryBridgeBasicByParentId(id) {
      this.$api.bridge.queryBridgeBasicByParentId({ groupId: id }).then(res => {
        if (res.data.success) {
          this.tableData.forEach((item, index) => {
            if (id === item.id) item.children = res.data.data[0];
          });
        }
      });
    },
    handleSuccessRender(res, file) {
      this.ruleForm.realisticPictureList.push({
        path: res.data.successFiles[0].filePath,
        id: res.data.successFiles[0].id
      });
    },
    removeRender() {
      this.ruleForm.realisticPictureList = [];
    },
    // 新增弹框 
    addEquipment(val) {
      this.addtitle = "新增桥联";
      this.$refs["ruleForm"].resetFields();
      this.dialogVisible = true;
      this.groupId = val;
    },
    //编辑桥梁
    edit(val) {
      this.addtitle = "修改桥联";
      this.changeStandardId(val.standardId);
      if (val.maintenanceType === "0") {
        this.typeList = this.typeList1;
      } else {
        this.typeList = this.typeList2;
      }
      if (val.municipalityCode && val.municipalityCode !== "") {
        this.changeRuleRegion(val.provinceCode);
      }
      if (val.regionCode && val.regionCode !== "") {
        this.changeRuleCity(val.municipalityCode);
        this.changeRuleArea(val.regionCode);
      }
      let imageUrl = this.download + val.realisticPictureList[0].path;
      let obj = {
        name: "111.png",
        url: imageUrl
      };
      this.imgList = [obj]
      this.ruleForm = JSON.parse(JSON.stringify(val))
      this.dialogVisible = true;
    },
    //删除桥梁
    removeBridge(val) {
      this.$confirm("此操作将删除桥联, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$api.bridge.deleteBridgeLinkById({ id: val.id }).then(res => {
            if (res.data.success) {
              this.$vs.notify({
                text: "删除成功",
                color: "success"
              });
              this.queryAllBridgeLink();
            }
          });
        })
        .catch(() => {});
    },
    resetBridge() {
      this.ruleForm = {
        name: "",
        code: "",
        bridgeTypeId: "",
        bridgeTypeName: "",
        bridgeKindId: "",
        bridgeKindName: "",
        length: "",
        address: "",
        lat: "",
        lng: "",
        status: 1,
        desc: "",
        maintenanceType: "",
        maintenanceLevel: "",
        regionCode: "",
        municipalityCode: "",
        provinceCode: "",
        regionName: "",
        municipalityName: "",
        provinceName: "",
        standardId: "",
        standardName: "",
        realisticPictureList: []
      };
    },
    cancelFormSubmit() {
      this.dialogVisible = false;
      this.resetBridge();
    },
    //桥梁新增
    submit() {
      this.$refs["ruleForm"].validate(valid => {
        if (valid) {
          if (this.ruleForm.realisticPictureList.length > 0) {
            if (this.addtitle === "新增桥联") {
              this.$api.bridge
                .addBridgeLink({
                  ...this.ruleForm,
                  ownId: this.ownId,
                  pId: this.pId
                })
                .then(res => {
                  if (res.data.success) {
                    this.$vs.notify({
                      text: "新增桥联成功",
                      color: "success"
                    });
                    this.dialogVisible = false;
                    this.resetBridge();
                    this.queryAllBridgeLink();
                    this.$emit('setChange')
                  }
                });
            } else {
              let data = {
                name: this.ruleForm.name,
                code: this.ruleForm.code,
                bridgeTypeId: this.ruleForm.bridgeTypeId,
                bridgeTypeName: this.ruleForm.bridgeTypeName,
                bridgeKindId: this.ruleForm.bridgeKindId,
                bridgeKindName: this.ruleForm.bridgeKindName,
                length: this.ruleForm.length,
                address: this.ruleForm.address,
                lat: this.ruleForm.lat,
                lng: this.ruleForm.lng,
                status: this.ruleForm.status,
                desc: this.ruleForm.desc,
                maintenanceType: this.ruleForm.maintenanceType,
                maintenanceLevel: this.ruleForm.maintenanceLevel,
                regionCode: this.ruleForm.regionCode,
                municipalityCode: this.ruleForm.municipalityCode,
                provinceCode: this.ruleForm.provinceCode,
                regionName: this.ruleForm.regionName,
                municipalityName: this.ruleForm.municipalityName,
                provinceName: this.ruleForm.provinceName,
                standardId: this.ruleForm.standardId,
                standardName: this.ruleForm.standardName,
                realisticPictureList: this.ruleForm.realisticPictureList,
                id: this.ruleForm.id,
                ownId: this.ownId,
                pId: this.pId
              };
              this.$api.bridge.updateBridgeLinkById(data).then(res => {
                if (res.data.success) {
                  this.$vs.notify({
                    text: "修改桥联成功",
                    color: "success"
                  });
                  this.dialogVisible = false;
                  this.resetBridge();
                  this.queryAllBridgeLink();
                  this.$emit('setChange')
                }
              });
            }
          } else {
            this.$vs.notify({
              text: "请上传桥梁图片",
              color: "danger"
            });
          }
        }
      });
    },
      setAddress(){
      this.mapContent = true
       this.$nextTick(function() {
        var th = this;
        // 创建Map实例
        var map = new BMap.Map("mapContent");
        // 初始化地图,设置中心点坐标，
        map.centerAndZoom("南京", 15);
        var ac = new BMap.Autocomplete({
          //建立一个自动完成的对象
          input: "suggest",
          location: map
        });
        var myValue;
        ac.addEventListener("onconfirm", function(e) {
          //鼠标点击下拉列表后的事件
          var _value = e.item.value;
          myValue =
            _value.province +
            _value.city +
            _value.district +
            _value.street +
            _value.business;
          th.address = myValue;
          setPlace();
        });
        function setPlace() {
          map.clearOverlays(); //清除地图上所有覆盖物
          function myFun() {
            th.location = local.getResults().getPoi(0).point; //获取第一个智能搜索的结果
            map.centerAndZoom(th.location, 18);
            map.addOverlay(new BMap.Marker(th.location)); //添加标注
          }
          var local = new BMap.LocalSearch(map, {
            //智能搜索
            onSearchComplete: myFun
          });
          local.search(myValue);
        }
      })
    },
    cancel(){
      this.address = ''
      this.location = {
        lng:'',
        lat:''
      }
      this.mapContent = false
    },
    submitMap(){
      this.ruleForm.address = this.address
      this.ruleForm.lng = this.location.lng;
      this.ruleForm.lat = this.location.lat;
      this.cancel()
    }
  }
};
</script>
<style lang="scss">
.tangram-suggestion {
  z-index: 999999;
}
</style>
<style scoped lang="scss">
/deep/.el-table__header tr,
.el-table__header th {
  padding: 0;
  height: 30px;
}
/deep/.el-table__row {
  height: 30px;
}
/deep/.el-upload--picture-card {
  width: 60px;
  height: 60px;
  line-height: 60px;
  text-align: center;
  font-size: 28px;
}
/deep/.el-upload-list--picture-card .el-upload-list__item {
  width: 60px;
  height: 60px;
}
.bridge {
  width: 100%;
  .flexBetween {
    display: flex;
    justify-content: space-between;
    .paddingLeft {
      margin-left: 20px;
    }
  }
  .tableTop {
    margin-top: 20px;
  }
  .page {
    margin-top: 20px;
    text-align: center;
  }
}
.map_box {
  width: 640px;
  height: 140px;
  background: gainsboro;
  margin-top: 20px;
}
</style>